﻿using System.Security.Cryptography;
using System.Text;

namespace Infrastructure.Utils
{
    /*哈希函数可以把任意长度字符串计算出一个固定长度的字符串(16进制字符串)
     * 常见的有MD5，SHA1，SHA224，SHA384，SHA512
     * 特点：1，算法不可逆 2，极小概率碰撞 3，可穷举字典(最简单的Md5穷举量都是PB级别的)
     * 加盐可以防止穷举破解
     */
    public class HashHelper
    {
        #region MD5算法
        /// <summary>
        /// 16位MD5加密-小写
        /// </summary>
        public static string MD5_16(string source)
        {
            using var md5 = MD5.Create();
            return BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(source)), 4, 8).Replace("-", "").ToLower();
        }
        /// <summary>
        /// 32位MD5加密-小写
        /// </summary>
        public static string MD5_32(string source)
        {
            using var md5 = MD5.Create();
            byte[] hashValue = md5.ComputeHash(Encoding.UTF8.GetBytes(source));
            return ConvertHelper.ByteToHexString(hashValue);
        }
        #endregion

        #region  Sha1 sha256 sha512算法
        /// <summary>
        /// Sha1算法-小写40位
        /// 1：356A192B7913B04C54574D18C28D46E6395428AB
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Sha1(string value)
        {
            using var sha = SHA1.Create();
            byte[] hashValue = sha.ComputeHash(Encoding.UTF8.GetBytes(value));//20字节
            return ConvertHelper.ByteToHexString(hashValue);
        }
        /// <summary>
        /// Sha256算法-小写64位
        /// 1：6B86B273FF34FCE19D6B804EFF5A3F5747ADA4EAA22F1D49C01E52DDB7875B4B
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Sha256(string source)
        {
            using var sha = SHA256.Create();
            byte[] hashValue = sha.ComputeHash(Encoding.UTF8.GetBytes(source));
            return ConvertHelper.ByteToHexString(hashValue);
        }
        /// <summary>
        /// Sha512算法-小写128位
        /// 1：4DFF4EA340F0A823F15D3F4F01AB62EAE0E5DA579CCB851F8DB9DFE84C58B2B37B89903A740E1EE172DA793A6E79D560E5F7F9BD058A12A280433ED6FA46510A
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Sha512(string source)
        {
            using var sha = SHA512.Create();
            byte[] hashValue = sha.ComputeHash(Encoding.UTF8.GetBytes(source));
            return ConvertHelper.ByteToHexString(hashValue);
        }
        #endregion
    }
}
